// --------------------------------------------------------------------
//
// This is a Greasemonkey user script.
//
// To install, you need Greasemonkey: http://greasemonkey.mozdev.org/
// Then restart Firefox and revisit this script.
// Under Tools, there will be a new menu item to "Install User Script".
// Accept the default configuration and install.
//
// To uninstall, go to Tools/Manage User Scripts,
// select "TribalWars Enhancer v2", and click Uninstall.
//
// --------------------------------------------------------------------
// ==UserScript==
// @name           TribalWars Enhancer v3
// @version        3b-Beta
// @namespace      i.am.timas-at-gmail.com
// @description    Beta R105 - Ads Remover. 15x15 Map. Shortcuts Bar. TW-Tools quick-access. Multi-Language and more!
// @include        http://ro*.triburile.ro/*
// @include        http://en*.tribalwars.net/*
// @include        http://nl*.tribalwars.nl/*
// @include        http://cs*.divokekmeny.cz/*
// @include        http://sv*.tribalwars.se/*
// @include        http://s*.tribalwars.tld/*
// @include        http://pl*.plemiona.pl/*
// @include	      http://en*.ds.ignames.net/*
// @include        http://gr*.ds.ignames.net/*
// @include        http://gr*.fyletikesmaxes.gr/*
// @require config.js
// @require jQuery1.2.3.js
// @require languages.js
// @require plugins.serverSettingsAPI.js
// @require plugins.detectionProtect.js
// @require plugins.addComma.js
// @require plugins.addStyles.js
// @require plugins.addToolbar.js
// @require plugins.attackAgain.js
// @require plugins.attackcache.js
// @require plugins.clearPremium.js
// @require plugins.distancecalc.js
// @require plugins.enhanceOverview.js
// @require plugins.gameAlert.js
// @require plugins.inpagepopup.js
// @require plugins.mapexpand.js
// @require plugins.nobleCoins.js
// @require plugins.pluginManager.js
// @require plugins.RefillCoordinates.js
// @require plugins.quickattack.js
// @require plugins.BBCodesReport.js
// @require plugins.removeAds.js
// @require plugins.reportcache.js
// @require plugins.setAlias.js
// @require plugins.SnobBuildingResources.js
// @require plugins.traveltimes.js
// @require plugins.mailForumReply.js
// @require plugins.BBCodesTextArea.js
// @require plugins.colorRankings.js
// @require plugins.TWMapIntegration.js
// @copyright      Copyright (c) 2007 - 2008, Gelu Kelu, Timas, Mog, ocdcsv, Jelian
// ==/UserScript==
// If we want debug info this has to exist and be 1, 2 or 3
var DEBUG = 1;

// Reset these parameters each time the script is run to ensure when using 
// another player ID the information is updated each time script is executed
// GM_setValue("TWE_PlayerID", "");

/* UNCOMMENT FOR DETECTION BLOCKER - Someone else please look at this, JelianSD
if(document.body.innerHTML.match(/setTimeout/g)) for(v in unsafeWindow) {
	if(typeof unsafeWindow[v]=='function') unsafeWindow[v] = function() {return false;};
}
*/

// --------------------------------------------------------------------
// Function : Old style tag fetcher
// --------------------------------------------------------------------
function $$(tag_name){
	return document.getElementsByTagName(tag_name);
}

// --------------------------------------------------------------------
// Output function, alternative to alert, logs to firebug console
// --------------------------------------------------------------------
function log(lvl, arg) {
	if (DEBUG && DEBUG !== 0) {
		if (DEBUG > 0 && lvl == 1) { console.log('[error]: '+arg); }
		if (DEBUG > 1 && lvl == 2) { console.log('[failure]: '+arg); }
		if (DEBUG > 2 && lvl == 3) { console.log('[message]: '+arg); }
	} else { return; }
}

// --------------------------------------------------------------------
// Make remote calls
// --------------------------------------------------------------------
function ajax(url, type, async) {
	var xhReq = new XMLHttpRequest();
	if (type != "POST") { type = "GET"; }
	if (async !== true) { async = false; }
	xhReq.open(type, url, async);
	xhReq.send(null);
	log(3, "XMLHttpRequest to "+url);
	return xhReq;
}

// --------------------------------------------------------------------
// Set a temporary variable
// --------------------------------------------------------------------
function setVar(name, new_val){
	if (typeof unsafeWindow == "object") {
		unsafeWindow[name] = new_val;
		log(3, name+' set into unsafeWindow [ setVar ]');
	} else if(TW_Is_Opera) {
		window[name] = new_val;
	}
}

// --------------------------------------------------------------------
// Read a temporary variable
// --------------------------------------------------------------------
function getVar(name) {
	if (typeof unsafeWindow == "object") {
		return unsafeWindow[name];
	} else {
		return window[name];
	}
}

// --------------------------------------------------------------------
// Set a function to run in the unsafe area
// --------------------------------------------------------------------
function setFunc(func, new_func) {
	if (typeof unsafeWindow == "object") {
		unsafeWindow[func] = new_func;
		log(3, func+' set into unsafeWindow [ setFunc ]');
	} else if(TW_Is_Opera) {
		window[func] = new_func;
	}
}

// --------------------------------------------------------------------
// Get a function from the unsafe area
// --------------------------------------------------------------------
function getFunc(func){
	if (typeof unsafeWindow == "object") {
		return unsafeWindow[func];
	} else {
		return window[func];
	}
}

// --------------------------------------------------------------------
// Check if we're using Opera or Firefox
// --------------------------------------------------------------------
function isOpera() {
	return $.browser.opera;
}

// --------------------------------------------------------------------
// Persistent Storage spread over worlds for one user
// --------------------------------------------------------------------
function setValueGlobal(key, new_val) {
	if(!isOpera()){

		// CODE TO REGISTER USER VARIABLES
		var storedPrefs = eval(GM_getValue("TWE_"+twe.Unique()+"_storedPrefsGlobal"));
		if (new String(storedPrefs) == 'undefined') { storedPrefs = {}; }
		storedPrefs[key] = 1;
		GM_setValue("TWE_"+twe.Unique()+"_storedPrefsGlobal", uneval(storedPrefs));
		// END CODE TO REGISTER VARIABLES


		GM_setValue("TWE_"+twe.myID()+"_"+key, uneval(new_val));
		return;
	}
	// Opera patch
	document.cookie = escape(key) + "=" + escape(new_val) + ";expires=" + (new Date((new Date()).getTime() + 31536000000)).toGMTString() + ";path=/";
}

// --------------------------------------------------------------------
// Persistent Storage for a single world
// --------------------------------------------------------------------
function setValue(key, new_val) {

	// CODE TO REGISTER USER VARIABLES
	var storedPrefs = eval(GM_getValue("TWE_"+twe.Unique()+"_storedPrefs"));
	if (new String(storedPrefs) == 'undefined') { storedPrefs = {}; }
	storedPrefs[key] = 1;
	GM_setValue("TWE_"+twe.Unique()+"_storedPrefs", uneval(storedPrefs));
	// END CODE TO REGISTER VARIABLES	

	GM_setValue("TWE_"+twe.Unique()+"_"+key, uneval(new_val));
}

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
function getValueGlobal(key) {
	if(!isOpera()) {
		return eval(GM_getValue("TWE_"+twe.myID()+"_"+key));
	}
	// Opera patch
	var all_cookies = document.cookie.split("; ");
	for(kk=0; kk<all_cookies.length; kk++){
		var this_cookie = all_cookies[kk];
		var tmp = this_cookie.split("=");
		if(tmp[0] == key){
			return unescape(tmp[1]);
		}
	}
	return null;
}

// --------------------------------------------------------------------
// Read from persistent storage, world specific
// --------------------------------------------------------------------
function getValue(key) {

	return eval(GM_getValue("TWE_"+twe.Unique()+"_"+key));
}

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
function delValue(key) {
	//key = key;
	if(!getValue(twe.Unique()+"_"+key)) { return; }
	if(!isOpera()) { GM_setValue("TWE_"+twe.Unique()+"_"+key, ""); }
	// Opera patch
	document.cookie = key + '=;expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

// --------------------------------------------------------------------
// Plugin Settings Storage functions - JelianSD
// --------------------------------------------------------------------
var PluginValues = new Array();
function setValuePlugin(key,value) {
	PluginValues = getValue("PluginVariables");
	if(PluginValues) {
		currentIndex = PluginValues.indexOf(key.toString());
		currentLength = PluginValues.length;
		if(currentIndex!=-1) {
			PluginValues[currentIndex+1]=value;
		} else {
			PluginValues[currentLength]=key.toString();
			PluginValues[currentLength+1]=value;
		}
	} else {
		var PluginValues = new Array();
		PluginValues[0]=key.toString();
		PluginValues[1]=value;
	}
	setValue("PluginVariables",PluginValues);
}
function getValuePlugin(key) {
	PluginValues = getValue("PluginVariables");
	if(PluginValues) {
		currentIndex = PluginValues.indexOf(key.toString());
		if(currentIndex!=-1) return PluginValues[currentIndex+1];
	}
	return null;
}
// --------------------------------------------------------------------
// End of Plugin Settings Storage functions - JelianSD
// --------------------------------------------------------------------

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
function array_flip( trans ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: array_flip( {a: 1, b: 1, c: 2} );
    // *     returns 1: {1: 'b', 2: 'c'}
	var tmp_ar = {};
	for(var key in trans ) {
		tmp_ar[trans[key]] = key;
	}
	return tmp_ar;
}


// --------------------------------------------------------------------
// Function : Xpath
// --------------------------------------------------------------------

function xpathGetFirst(xpath) {
	return document.evaluate(xpath,document,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue;
}

// XPath helper from http://wiki.greasespot.net/Code_snippets#XPath_helper
function xpathGetAll(p, context) {
	if (!context) context = document;
	var i, arr = [], xpr = document.evaluate(p, context, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);
	for (i = 0; item = xpr.snapshotItem(i); i++) arr.push(item);
	return arr;
}


// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
personals = {
	villageGroups : function() { // Grab all the available groups
		if (! getValue("villageGroups") || getValue("villageGroups") == 'undefined') {
			return [];
		} else {
			var val = getValue("villageGroups");
			var grps = [];
			for (i = 0; i < val.length; i++) {
				var grpinfo = getValue("GroupInfo_"+val[i]);
				if (new String(grpinfo) != 'undefined' && new String(grpinfo) != '') {
					var tmp = grpinfo;
					if (!tmp.show) { tmp.show = '1'; }
					grps.push('({"id":"'+val[i]+'" ,"name":"'+tmp.name+'","show":"'+tmp.show+'"})');
				}

			}
			return grps;
		}
	},

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
 getUserVillages : function() { // Grab the users villages 

	var villages = {};

	twePremium = ($("a[href*=memo]").length > 0) ? true : false;
	if (twePremium) {
		//if ($("a:first").length > 0) {
			firstvilid = $("a:first").attr('href').replace(/^(.*)village=([^&]+)(.*)/i, "$2");
	
			currentGroup = $("#menu_row2 a[href^=javascript:popup_scroll]").attr("href").replace(/(.+)group_id=([^&]+)(.+)/gi,"$2");
			currentMode  = $("table.main table.vis td.selected a").attr("href").replace(/(.+)mode=(.+)/gi, "$2");
			cUrl = twe.Server+'/game.php?village='+firstvilid+'&screen=overview_villages&mode='+currentMode+'&group='+currentGroup+'&page=0&';
	
			pUrl = twe.Server+'/game.php?village='+firstvilid+'&screen=overview_villages&mode=groups&group=0&page=-1&';
			pData = '';
			pType = 'html';
	
	
			jQuery.get( pUrl, pData, function(xhr) {
			$("tr[class^=row_]", xhr).each(function() {
	
				tmpId = $(this).html().match(/village=([^&]+)/);
				tmp = $(this).html().match(/>(.+) \(([^|]+)\|([^)]+)\) K([0-9]+)</);
				tmpName = tmp[1];
				tmpY = tmp[2];
				tmpX = tmp[3];
				tmpK = tmp[4];
	
	
				tmpGrpCount = $("td:eq(1)", this).html();
				tmpGrps = $("td:eq(2)", this).html().split("; ");
			
				villages[tmpId[1]] =  {id: tmpId[1], 
						name: tmp[1],
						x: parseInt(tmp[2]),
						y: parseInt(tmp[3]),
						continent: tmp[4],
						premGroupCount : parseInt(tmpGrpCount),
						premGroups : tmpGrps
						};
			});
	
			setValue("myVillages", villages);
			}, pType );
	
			jQuery.get( cUrl );
		//} else { alert("failed"); }
	} else {
	
	var villageSet = $("table.vis tr[class^='nowrap row_']");

	 for (i = 0; i < villageSet.length; i++) { // loop through the found links
		 var cells = villageSet[i].getElementsByTagName("td");

		 var tmpId = cells[0].innerHTML.match( /village=([^&]+)/ );
		 var tmpDetails = cells[0].innerHTML.match( /">(.+) \((-?\d+)\|(-?\d+)\)(?: K(\d+))?<\/sp/ );
		 var tmpPoints = cells[1].innerHTML.replace(/<span(.+)>.<\/span>/gi, ".");
		 var tmpPointsInt = parseInt(cells[1].innerHTML.replace(/<span(.+)>.<\/span>/gi, ""));

		 var vilinfo = new String(getValue("villageinfo_"+tmpId[1]));

		 if (vilinfo != 'undefined') {
			 vilinfo = vilinfo.split(",");
			 var tmpGrp = vilinfo[0];
			 var tmpAlias = decodeURIComponent(vilinfo[1]);
			 tmpAlias = tmpAlias.replace(/%/g, tmpDetails[1]);
		 } else {
			 var tmpGrp = '0';
			 var tmpAlias = '';
		 }

		 villages[tmpId[1]] =  {id: tmpId[1], 
								name: tmpDetails[1],
								x: parseInt(tmpDetails[2]),
								y: parseInt(tmpDetails[3]),
								continent: tmpDetails[4],
								points: tmpPoints,
								pointsint: tmpPointsInt,
								group: tmpGrp,
								alias: tmpAlias,
								resourcesHTML: cells[2].innerHTML+" <img src=\"graphic/res.png\" title=\"Warehouse limit\" alt=\"\">"+cells[3].innerHTML
								};
		 //log(3, "villages="+uneval(villages));
	 }
	 villages.length = villageSet.length;
	

                // And now set the result into the memory
	 setValue("myVillages", villages);
}
//alert(uneval(villages));
                //return twe.myVillages(); // return it here
 },

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
 getCurrentVillage : function() { // Grab the currently selected village
	 if (twe.curVillage === null) {
		 try {
		 		var cur = $("a[href*='village=']:first").attr("href");
				cur = cur.match(/village=([^&]\d+)/i)[1];
				twe.curVillage = cur;
		 } catch(e) {
			 log(1, "Failed to properly execute getCurrentVillage. js error:\n"+e);
			 twe.curVillage = null;
		 }
		 /*
		 
			 var tmp = cur[0].getAttribute("href").match(/village=([^&]+)/);
			 twe.curVillage = tmp[1];
		 */
	 }
	 return twe.curVillage;
 },

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
 getImageBase : function() { // Grab the base of the images
	 if (! getValueGlobal("imgBase") || getValueGlobal("imgBase").length < 5 || getValueGlobal("imgBase") == 'undefined') {
		 return "/graphic/";
	 } else {
		 return getValueGlobal("imgBase");
	 }
 }
};

var CurrentUserLocation = location.href+"";
// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
twe = { // TWE data
	myID : function() { // My user ID
		if(!GM_getValue("TWE_PlayerID")) {
			xhReq = ajax(twe.Server+"/guest.php?screen=info_village&id="+personals.getCurrentVillage(), "GET");
			var tmp = xhReq.responseText.match( /info_player&amp;id=([^"]+)/ );
			var id = tmp && tmp[1] ? tmp[1] : null;
			GM_setValue("TWE_PlayerID", encodeURIComponent(id));
		}
		return GM_getValue("TWE_PlayerID");
	},


// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
 myVillages : function() { // My villages
	 if (twe.Screen == "overview_villages" || ! getValue("myVillages") || getValue("myVillages") === 'undefined') {
		 personals.getUserVillages();
	 }
	 return getValue("myVillages");
 },

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
 lang : function(field) { // Grab the language tag
	 TW_Lang = languages[twe.Language];
	 if(!TW_Lang) { TW_Lang = languages.en; }
	 if(TW_Lang[field]) {
		 return TW_Lang[field];
	 } else {
		 log(1, "Missing language tag for '"+field+"' in language '"+twe.Language+"'");
		 return '{'+field+'}';
	 }
 },

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
 getPlugins : function() { // Grab the enabled/disabled info for plugins

	 var val = getValue("plugins");
	 if (! val || val == 'undefined') {
		 return [];
	 } else {
		 return val;
	 }
 },

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
 setPlugin : function(name) { // Add or remove a plugin from the disabled list
	 var val = getValue("plugins");

	 if (! val || new String(val) == 'undefined') {
		 setValue("plugins", new Array(name));
		 log(2, "Disabled plugin: "+name);
	 } else {

		 if (val.indexOf(name) != -1) {
			 val.splice(val.indexOf(name), 1);
			 var tmp = val;

		 } else {
			 val.push(name);
			 tmp = val;
		 }

		 setValue("plugins", tmp);
		 log(2, "Switched status of plugin: "+name);
	 }
 },
 curVillage : null,

        // A unique string for each world per user

// --------------------------------------------------------------------
// Function : 
// --------------------------------------------------------------------
 Unique : function() { return twe.myID()+"_"+twe.World; }, // twe.myID() performs an XMLHttpRequest

        // Are we super duper premium members?
 Premium : ($("a[href*=memo]").length > 0) ? true : false,

        // Get the screen variable
 Screen : CurrentUserLocation.match(/screen=([^&]\w+)/i)[1],

        // Get the page we're viewing
 Page: CurrentUserLocation.match(/\/(\w+)\.php/i)[1],

        // Get the world we're playing
		// Changed from the replace onto match
		// World: location.href.replace(/^http:\/\/(\w+)\.(\w+)\.(\w+)\/(.*)$/i,"$1"),
 World: CurrentUserLocation.match(/http:\/\/(\w+)\./i)[1],

        // Get the language we're playing in
 Language: CurrentUserLocation.match(/http:\/\/(\w{2})/i)[1],

        // Get the server we're playing
 Server: CurrentUserLocation.match(/(.*)\/(.*)\.php/i)[1]
};

//// start timezone
// adapted from http://www.sdplastics.com/timezone.html
	dstZones = new Array ();
	qReport = new Array ();
	TableTimes = new Array();
	currentQuery = null;

	var Local = new Date();
	var GMToffset = Local.getTimezoneOffset();

	if (navigator.appName == "Netscape") {
		if (GMToffset < 0) {GMToffset = Math.abs(GMToffset)}
		else {GMToffset = GMToffset - (Math.abs(GMToffset) *2)};
	};
	var newline= (navigator.appVersion.lastIndexOf('Win') != -1) ? "\r\n" : "\n";

	function Into24hrs (time) {
		if ( time > 1440)
		{ time -= 1440}
		else
		{ if ( time <0) { time = 1440 + time } };
		return time;
	} // --- Into24hrs

	function GMTnow (GMT) {
		var time = new Date();
		hrs = time.getHours();
		mins = time.getMinutes();
		GMT = (hrs*60 + mins) - GMToffset;
		GMT = Into24hrs(GMT);
		return GMT;
	}

	function formatRelative (time) {
		var Report = null;
		var Direction  = (time > 0) ? " ahead" : " behind";
		time = Math.abs (time);
		var Hours = Math.floor (time/60);
		var Mins = (time - Hours * 60);
		Report = Hours + "h ";
		if (Mins != 0) {Report=Report+Mins + "m "};
		Report = Report+ Direction;
		if (time== 0) {Report="Same Time"};
		return Report;
	}; 

	function formatTime (time) {
		var fHours = Math.floor (time/60) ;
		if (fHours <= 9) {fHours = "0" + fHours}; 
		var fMins = time - (fHours * 60);
		if (fMins <= 9) {fMins = "0" + fMins}; 
		var fTime = fHours + ":" + fMins;
		return fTime;
	};

	function CheckDST () {
		var uNow = new Date();
		var uMonth = uNow.getMonth();
		var uDate = uNow.getDate();
		var uDay = uNow.getDay();

		var FirstSun8Feb = ( (uMonth == 1 && uDate > 14) || uMonth > 1 ) ? true : false;
		if ((uMonth == 1)&&(uDate >= 8)) {
			var DaysLeft = 14  - uDate;
			FirstSun8Feb = (uDay + DaysLeft <= 6) ? true : false;
		};

		var FirstSun15Mar = ( (uMonth == 2 && uDate > 21) || uMonth > 2 ) ? true : false;
		if ((uMonth == 2)&&(uDate >= 15)) {
			DaysLeft = 21  - uDate;
			FirstSun15Mar = (uDay + DaysLeft <= 6) ? true : false;
		};

		var LastSunMar = (uMonth > 2) ? true : false;
		if ((uMonth == 2)&&(uDate >= 25)) {
			DaysLeft = 31  - uDate;
			LastSunMar = (uDay + DaysLeft <= 6) ? true : false;
		};

		var FirstSunApr = ( (uMonth == 3 && uDate > 7) || uMonth > 3 ) ? true : false;
		if ((uMonth == 3)&&(uDate <= 7)) {
			var DaysGone = 7  - uDate;
			FirstSunApr = (uDay - DaysGone >0) ? true : false;
		};

		var LastSunSep = (uMonth > 8) ? true : false;
		if ((uMonth == 8)&&(uDate >= 24)) {
			DaysLeft = 30  - uDate;
			LastSunSep = (Day + DaysLeft <= 6) ? true : false;
		};

		var FirstSunOct = ( (uMonth == 9 && uDate > 7) || uMonth > 9  ) ? true : false;
		if (uMonth == 9 && uDate <= 7) {
			DaysGone = 7  - uDate;
			FirstSunOct = (uDay - DaysGone >0) ? true : false;
		};

		var FirstSun15Oct = ( (uMonth == 9)&&(uDate > 21) || (uMonth > 9) ) ? true : false;
		if ( uMonth == 9 && (uDate >= 15 || uDate <= 21) ) {
			DaysLeft = 21  - uDate;
			FirstSun15Oct = (uDay + DaysLeft <= 6) ? true : false;
		};

		var LastSunOct = (uMonth > 9) ? true : false;
		if ((uMonth == 9)&&(uDate >= 25)) {
			DaysLeft = 31  - uDate;
			LastSunOct = (uDay + DaysLeft <= 6) ? true : false;
		};

		dstZones[0] = "X";
		dstZones[1] = "?";
		dstZones[2] =  (FirstSunApr && !LastSunOct) ? "Y" : "N";//usa/canada
		dstZones[3] =  (LastSunMar && !LastSunOct) ? "Y" : "N";//uk/europe
		dstZones[4] =  (LastSunOct || !LastSunMar) ? "Y" : "N";//aus	
		dstZones[5] =  (FirstSunOct || !LastSunMar) ? "Y" : "N";//aus-tasmania
		dstZones[6] =  (FirstSunOct || !FirstSun15Mar) ? "Y" : "N";//nz
		dstZones[7] =  (LastSunMar && !LastSunSep) ? "Y" : "N";//russia

	} 


	function qHandler(ZoneData) {
		qReport[0] = ""; qReport[1] = ""; qReport[2] = ""; qReport[3] = "";	

		var qGMTparse = parseFloat(ZoneData);
		var qGMToffset_hrs = parseInt(qGMTparse, 10) ; 
		var qGMToffset_min= parseInt ( Math.round((qGMTparse-qGMToffset_hrs) * 100), 10);
		var qDSTperiod = ZoneData.charAt (ZoneData.length - 1);
		var qGMTperiod = 1440/60;
		if ( (qGMToffset_hrs > 12) || (qGMToffset_hrs <-11) ) {qReport[0] = "BAD DATA"; return};
		if (qDSTperiod > dstZones.length) {qReport[3] = "BAD DATA"};


		var relGMT = (qGMToffset_hrs * 60) + qGMToffset_min; 
		if (dstZones [qDSTperiod] == "Y") {relGMT += 60; qReport[3] = "Yes (+1 hour)"};
		if (dstZones [qDSTperiod] == "N") {qReport[3] = "No"};
		if (dstZones [qDSTperiod] == "X") {qReport[3] = "n/a"};
		if (dstZones [qDSTperiod] == "?") {qReport[3] = "uncertain"};

		var qPlaceTotMins = GMTnow (qPlaceTotMins);
		qPlaceTotMins += relGMT; 
	//qPlaceTotMins = Into24hrs (qPlaceTotMins);
		qReport[0] = qPlaceTotMins;
		qReport[2] = formatRelative (relGMT);

		var relLoc = relGMT - GMToffset;
		qReport[1] = formatRelative (relLoc);
	}

	function getTime(ZoneData) {
		var qGMTparse = parseFloat(ZoneData);
		var qGMToffset_hrs = parseInt(qGMTparse, 10) ; 
		var qGMToffset_min= parseInt ( Math.round((qGMTparse-qGMToffset_hrs) * 100), 10);
		var qDSTperiod = ZoneData.charAt (ZoneData.length - 1);
		var qGMTperiod = 1440/60;
		if ( (qGMToffset_hrs > 12) || (qGMToffset_hrs <-11) ) {qReport[0] = "BAD DATA"; return};
		if (qDSTperiod > dstZones.length) {qReport[3] = "BAD DATA"};

		var relGMT = (qGMToffset_hrs * 60) + qGMToffset_min; 

		if (dstZones [qDSTperiod] == "Y") {relGMT += 60;};

		time = GMTnow()+relGMT;
		var fHours = Math.floor (time/60) ;
		var fMins = time - (fHours * 60);
		var ret = new Date();
		var dsthours = ret.getHours();
		var dstmins = ret.getMinutes();
		var mins_since_midnight = dsthours*60 + dstmins;
		if (fHours>24) { fHours = fHours - 24;}
		if (fHours<-24) { fHours = fHours + 24;}
		ret.setHours(fHours);
// Added code to adjust daylight savings and timezone issues
		if (mins_since_midnight < (GMToffset - relGMT)) { ret.setDate(ret.getDate()-1); }
 		ret.setMinutes(fMins);
		return ret;	
	}

	function qReply (ZoneData) {
	
		currentQuery = ZoneData;
		qHandler (ZoneData);
		alert(	"Current Time = " +  formatTime ( qReport[0] )
				+ newline + "Relative to Local = "+ qReport[1] 
				+ newline + "Relative to GMT = "+ qReport[2]
				+ newline + "Using Daylight Savings? = " + qReport[3]
				+ newline + "ServerTime = "+ servertime
				+ newline + "ServerTime formatTime = "+ formatTime (servertime )
				+ newline + "ServerTime.getTime() = "+ servertime.getTime()); 

	}


	CheckDST();
//qHandler = "1%3";
	servertime=getTime("1%3");
//qReply("1%3");

//// end timezone


// Kicker
	for(var pname in plugins) {
		var plugs = twe.getPlugins();
		if (plugs.indexOf(pname) == -1) {
			var variables = plugins[pname]["variables"];
			if(variables) {
				for(var Cvariable in variables) {
					CurrentName = new String(Cvariable);
					if(CurrentName=="tooltip"||CurrentName=="desc") continue;
					OriginalValue = variables[Cvariable];
					if(!getValuePlugin(CurrentName) && getValuePlugin(CurrentName)!=false && getValuePlugin(CurrentName)!=true) {
						if(OriginalValue.constructor.toString().indexOf("Array") != -1) OriginalValue=OriginalValue[0];
						setValuePlugin(CurrentName,OriginalValue);
					}
				}
			}
			var func = plugins[pname]["enhance_"+twe.Page];
			if(func) { func(); }
			func = plugins[pname]["enhance_"+twe.Page+"_"+twe.Screen];
			if(func) { func(); }
		}
	}

